<template>
	<div>
		<div class="text-center my-3">
			车辆配置
		</div>
		<van-form @submit="onSubmit">
			<van-cell-group inset>
				<van-field
					v-model="config.wifi"
					name="wifi"
					label="wifi名称"
					placeholder="wifi名称"
					:rules="[{ required: true, message: '请填写wifi名称' }]"
				/>
				<van-field
					v-model="config.mqtt.host"
					name="host"
					label="订阅地址"
					placeholder="订阅地址"
					:rules="[{ required: true, message: '请填写订阅地址' }]"
				/>
				<van-field
					v-model="config.mqtt.port"
					name="port"
					label="订阅端口号"
					placeholder="订阅端口号"
					:rules="[{ required: true, message: '请填写订阅端口号' }]"
				/>
				<van-field
					v-model="password"
					type="password"
					name="密码"
					label="密码"
					placeholder="密码"
					:rules="[{ required: true, message: '请填写密码' }]"
				/>
				<van-field
					v-model="car"
					is-link
					readonly
					label="车辆"
					placeholder="选择车辆"
					@click="showPicker = true"
				/>
				<van-popup v-model:show="showPicker" round position="bottom">
					<van-picker
						:columns="columns"
						@cancel="showPicker = false"
						@confirm="onConfirm"
					/>
				</van-popup>
			</van-cell-group>
			<div style="margin: 16px;">
				<van-button round block type="primary" native-type="submit">
					配置二维码生成
				</van-button>
			</div>
		</van-form>

		<div class="text-center">
			<van-image
				v-show="showQr"
				class="w-64 h-64"
				:src="qrCode"
			/>
		</div>

	</div>
</template>

<script setup>
import { onMounted, ref } from "vue";
import { closeToast, showLoadingToast, showToast } from "vant";
import { getCarConfigQrCode, getCarList } from "@/api/car.js";

const password = ref("");
const showPicker = ref(false);
const car = ref("");
const showQr = ref(false);
const qrCode = ref("");
const config = ref({
	wifi:"",
	ssid: "",
	password: "",
	mqtt: {
		host: "",
		port: "",
	},
});
const onSubmit = async (values) => {
	showLoadingToast("生成中...");
	const res = await getCarConfigQrCode(config.value)
	closeToast();
	if (res){
		qrCode.value = res.data;
		showQr.value = true;
	}
};

const columns = ref([]);
const onConfirm = ({ selectedValues }) => {
	config.value.ssid = selectedValues[0]
	showPicker.value = false;
	car.value = columns.value.find((item) => item.value === selectedValues[0]).text
};


onMounted(()=>{
	getCarList().then((res)=>{
		if (res){
			columns.value = res.data.map((item)=>{
				return {
					text: item.name,
					value: item.id,
				}
			})
		}
	})
})
</script>

<style scoped>

</style>
